/*
                        *********************
*************************** C SOURCE FILE ************************************
**                      *********************                               **
**                                                                          **
*/

#define _CLIENT_C_SRC

/****************************************************************************/
/**                                                                        **/
/** MODULES USED                                                           **/
/**                                                                        **/
/****************************************************************************/

#include "client.h"

/****************************************************************************/
/**                                                                        **/
/** DEFINITIONS AND MACROS                                                 **/
/**                                                                        **/
/****************************************************************************/

#define BAUDRATE B38400
#define FALSE 0
#define TRUE 1

/****************************************************************************/
/**                                                                        **/
/** TYPEDEFS AND STRUCTURES                                                **/
/**                                                                        **/
/****************************************************************************/


/****************************************************************************/
/**                                                                        **/
/** PROTOTYPES OF LOCAL FUNCTIONS                                          **/
/**                                                                        **/
/****************************************************************************/

void signal_handler_IO (int status);    //definition of signal handler


/****************************************************************************/
/**                                                                        **/
/** EXPORTED VARIABLES                                                     **/
/**                                                                        **/
/****************************************************************************/


/****************************************************************************/
/**                                                                        **/
/** GLOBAL VARIABLES                                                       **/
/**                                                                        **/
/****************************************************************************/

volatile int STOP=FALSE;
int wait_flag=TRUE;                  //TRUE while no signal received
int status,state = READ;
int place = 0;
FILE *input;
FILE *output;

/****************************************************************************/
/**                                                                        **/
/** EXPORTED FUNCTIONS                                                     **/
/**                                                                        **/
/****************************************************************************/



/****************************************************************************/
/**                                                                        **/
/** LOCAL FUNCTIONS                                                        **/
/**                                                                        **/
/****************************************************************************/
main()
{
	char Param_strings[7][80];
	char message[90];

	int16s 	sockfd;
	int16u 	len,lenge;
	int16u	answer;
	struct 	sockaddr_in address;

	int fd, tty, c, result, i, error;
	char In1, Key;
	struct termios oldtio, newtio;       //place for old and new port settings for serial port
	struct termios oldkey, newkey;       //place tor old and new port settings for keyboard teletype
	struct sigaction saio;               //definition of signal action
	char buf[200],data[200],*p;                       //buffer for where data is put

	input = fopen("/dev/tty", "r");      //open the terminal keyboard
	output = fopen("/dev/tty", "w");     //open the terminal screen

	tty = open("/dev/tty", O_RDWR | O_NOCTTY | O_NONBLOCK); //set the user console port up
	tcgetattr(tty,&oldkey); // save current port settings   //so commands are interpreted right for this program
	// set new port settings for non-canonical input processing  //must be NOCTTY
	newkey.c_cflag = BAUDRATE | CRTSCTS | CS8 | CLOCAL | CREAD;
	newkey.c_iflag = IGNPAR;
	newkey.c_oflag = 0;
	newkey.c_lflag = 0;       //ICANON;
	newkey.c_cc[VMIN] = 1;
	newkey.c_cc[VTIME] = 0;
	tcflush(tty, TCIFLUSH);
	tcsetattr(tty,TCSANOW,&newkey);

	//open the device(com port) to be non-blocking (read will return immediately)
	fd = open("/dev/ttyS1", O_RDWR | O_NOCTTY | O_NONBLOCK);

	//install the serial handler before making the device asynchronous
	saio.sa_handler = signal_handler_IO;
	sigemptyset(&saio.sa_mask);   //saio.sa_mask = 0;
	saio.sa_flags = 0;
	saio.sa_restorer = NULL;
	sigaction(SIGIO,&saio,NULL);

	// allow the process to receive SIGIO
	fcntl(fd, F_SETOWN, getpid());
	// Make the file descriptor asynchronous (the manual page says only
	// O_APPEND and O_NONBLOCK, will work with F_SETFL...)
	fcntl(fd, F_SETFL, FASYNC);

	tcgetattr(fd, &oldtio); // save current port settings 
	// set new port settings for canonical input processing 
	newtio.c_cflag = B9600 | CRTSCTS | CS8 | 0 | 0 | 0 | CLOCAL | CREAD;
	newtio.c_iflag = IGNPAR;
	newtio.c_oflag = 0;
	newtio.c_lflag = 0;       //ICANON;
	newtio.c_cc[VMIN]=1;
	newtio.c_cc[VTIME]=0;
	tcflush(fd, TCIFLUSH);
	tcsetattr(fd,TCSANOW,&newtio);

	// Create a socket for the client. 
	sockfd = socket(AF_INET, SOCK_STREAM, 0);
	// Socket name, as agreed with the server.
	address.sin_family = AF_INET;
	address.sin_addr.s_addr = inet_addr("192.168.1.245");
	address.sin_port = 22;
	len = sizeof(address);

	// Connect our socket to the server's socket.
	result = connect(sockfd, (struct sockaddr *)&address, len);
	if(result == -1)
	{
		perror("OOPS!!: connect function error");
		exit(1);
	}

	
	// loop while waiting for input. normally we would do something useful here
	while(STOP==FALSE)
	{
		switch(state)
		{
			case READ :

				clr(buf,200);
				if (wait_flag==FALSE)  //if input is available
				{

					result = read(fd,buf,200);
					if (result>0)
					{
						p = buf;
						printf("%s\r\n",buf);
					i=0;
					while(i<200)
					{
						if(buf[i]==0x0D)
						{
							printf("before CR\r\n");
						}
						i++;
					}
					i=0;
					while(i<200)
					{
						if(buf[i]==0x0A)
						{
							printf("before LF\r\n");
						}
						i++;
					}
						while(*p)
						{
							if(buf[0]==0x0D)
							{
								data[place]='\0';
								printf("Press enter\r\n");
								printf("Data is %s",data);
								place = 0;
								state = SEND;
							}
							else if(buf[0]==0x1b)
							{
								state = NON;
								STOP=TRUE;
							}
							else if(buf[0]!=0x0D)
							{
								data[place] = *p;
								place++;
							}
							p++;
						}
					}
					wait_flag = TRUE;      /* wait for new input */
				}
			break;
			case SEND :printf("\r\nSEND data\r\n");
				write(sockfd,data,200);
				clr(data,200);
				clr(buf,200);
				result = read(sockfd,buf,200);
				if(result == -1)
				{
					printf("Server do not reply DATA\r\n");
				}
				else
				{
					printf("Server reply DATA\r\n");
					printf("%s\r\n",buf);
					lenge = strlen(buf);
				write(fd,"**************************************************\r\n",52);
				write(fd,buf,lenge);
				write(fd,"**************************************************\r\n",52);
					
				}
				state = READ;
			break;
		}
	}
	
	tcsetattr(fd,TCSANOW,&oldtio);
	tcsetattr(tty,TCSANOW,&oldkey);
	close(tty);
	close(fd);        //close the com port

	fclose(input);
	fclose(output);

	return 0;
}

void signal_handler_IO (int status)
{
	wait_flag = FALSE;
}




/****************************************************************************/
/**                                                                        **/
/** EOF                                                                    **/
/**                                                                        **/
/****************************************************************************/

